package com.zhangsun.yueBoot.admin.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangsun.yueBoot.admin.user.entity.RegisterUser;
import com.zhangsun.yueBoot.admin.user.entity.User;
import com.zhangsun.yueBoot.admin.user.mapper.UserMapper;
import com.zhangsun.yueBoot.admin.user.service.UserService;
import com.zhangsun.yueBoot.commons.base.service.impl.BaseServiceImpl;
import com.zhangsun.yueBoot.framework.expection.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 用户service实现
 */
@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(RegisterUser registerUser) throws BusinessException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_no", registerUser.getUserNo());
        int hasUser = userMapper.selectCount(wrapper);
        if (hasUser > 0) {
            throw new BusinessException("该账号已存在，请换一个");
        }

        User user = new User();
        BeanUtils.copyProperties(registerUser, user);
        user.setPassword(new BCryptPasswordEncoder().encode(registerUser.getPassword()));
        user.setCreateTime(new Date());
        user.setModifyTime(new Date());
        user.setModifyTime(new Date());
        userMapper.insert(user);
    }

    @Override
    public void resetAdmin() {
        User user = new User();
        user.setId("0");
        user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        user.setModifyTime(new Date());
        userMapper.updateById(user);
    }

}
